<?php
namespace app\admin\controller;
use x\my\Captcha;
class Publics extends Base {
	//登录界面
	public function login() {
		if (is_post()) {
			$d = $this->post;
			$token = cookie('captcha_token');
			if (!Captcha::checkCaptcha($token, $d['code'])) {
				cookie('js_name', 'code');
				err('验证码错误!');
			}
      /* 获取用户数据 */
      $user = $this->db->query('select * from admin_user where username=? and website_id=?',[$d['username'], $this->web_site_id],1);
      if (empty($user) || (int)$user['status'] !== 0) {
          err('用户不存在或被禁用');
      }
      if($user['password'] != com_password($d['password'])){
          err('密码错误');
      }
      $token = token($user['id']);
      $data = [
          'id' => $user['id'],
          'token' => $token,
          'last_login_ip' => ip(),
          'last_login_time' => time(),
          'login_times' => $user['login_times']+1,
          'error_times' => 0,
      ];
      $this->db->update('admin_user',$data);
      cookie('token',$token);
			cookie('js_url', url('index/index'));
			cookie('js_msg', '登录成功!');
			return suc();
		}
		$this->fetch([], '', false);
	}
	//验证码
	public function captcha() {
		$token = token();
		cookie('captcha_token', $token);
		return Captcha::generate($token);
	}

	//退出
	public function logout() {
		$token = cookie('token');
		if ($token) {
			$this->db->update('admin_user', ['token' => ''], ['token=?', [$token]]);
		}
		cookie(null, null);
		session(null, null);
		r(url('publics/login'));
	}
	//后台菜单配置
	public function menudatas() {
		if (session("?arr_id")) {
			$arr_id = session("arr_id");
		} else {
			$menu = c('adminmenu');
			$arr_id = admin_menu_arr($menu, 0);
		}
		$rs = admin_menu_tree($arr_id, 0);
		return suc($rs);
	}
}
?>
